<template>
  <div class="container">
    <!-- 头部 -->
    <el-row type="flex" justify="start" style="margin-bottom: 20px;">
      <el-col :span="24">
        <span style="color: #fda6a6; font-size: 12px;">说明：目前支持学科和关键字条件筛选</span>
      </el-col>
      <el-col>
        <el-row type="flex" justify="end">
          <el-button type="success" size="small" icon="el-icon-edit" @click.native="$router.push('/questions/new')">新增试题</el-button>
        </el-row>
      </el-col>
    </el-row>

    <!-- 表单 -->
    <el-form :inline="true" :model="formList">
      <el-row type="flex" justify="end">
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="学科">
            <el-select placeholder="请选择" v-model="formList.discipline">
              <el-option :value="item.id" :label="item.subjectName" v-for="item in subjects" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="二级目录">
            <el-select placeholder="请选择" v-model="formList.directory">
              <el-option :value="item.directoryName" :label="item.directoryName" v-for="item in directory" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="标签">
            <el-select placeholder="请选择" v-model="formList.label">
              <el-option :value="item.tagName" :label="item.tagName" v-for="item in tags" :key="item.id"></el-option>
            </el-select>
          </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="关键字">
              <el-input v-model="formList.keyWords" placeholder="根据题干搜索" style="width: 222px;"></el-input>
            </el-form-item>
          </el-row>
        </el-col>
      </el-row>
      <el-row type="flex" justify="end">
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="试题类型">
            <el-select placeholder="请选择" v-model="formList.type">
              <el-option :value="item.value" :label="item.label" v-for="item in questionType" :key="item.label"></el-option>
            </el-select>
          </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="难度">
              <el-select placeholder="请选择" v-model="formList.difficulty">
                <el-option :value="item.value" :label="item.label" v-for="item in difficulty" :key="item.label"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="方向">
              <el-select placeholder="请选择" v-model="formList.direction">
                <el-option :value="item" :label="item" v-for="item, index in direction" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="录入人">
              <el-select placeholder="根据题干搜索" v-model="formList.person">
                <el-option :value="item.username" v-for="item in entryPeople" :key="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-row>
        </el-col>
      </el-row>
      <el-row type="flex">
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="题目备注">
              <el-input v-model.trim="formList.title" style="width: 222px;"></el-input>
            </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="企业简称">
              <el-input v-model.trim="formList.enterprise" style="width: 222px;"></el-input>
            </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item label="城市">
              <el-row type="flex" justify="space-around" :gutter="10">
                <el-col>
                  <el-select placeholder="请选择" style="width: 105px;" v-model="formList.city[0]">
                    <el-option :value="item.city" v-for="item in datas" :key="item.city" :label="item.city"></el-option>
                  </el-select>
                </el-col>
                <el-col>
                  <el-select placeholder="请选择" style="width: 105px;" v-model="formList.city[1]">
                    <el-option :value="item" v-for="item, index in area.area" :key="index" :label="item"></el-option>
                  </el-select>
                </el-col>
              </el-row>
          </el-form-item>
          </el-row>
        </el-col>
        <el-col>
          <el-row type="flex" justify="end">
            <el-form-item>
              <el-button size="small" @click="resetForm">清除</el-button>
              <el-button type="primary" size="small" @click="searchTopic">搜索</el-button>
            </el-form-item>
          </el-row>
        </el-col>
      </el-row>
    </el-form>

    <!-- 标签页切换 -->
    <el-tabs type="card" @tab-click="handleClick" v-if="isShow">
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <el-tab-pane label="待审核" name="reviewed"></el-tab-pane>
      <el-tab-pane label="已审核" name="approved"></el-tab-pane>
      <el-tab-pane label="已拒绝" name="reject"></el-tab-pane>
    </el-tabs>

    <!-- 提示：共多少条数据 -->
    <el-alert type="info" show-icon :closable="false" v-if="!isShow" :title="`一共有${filterList.length ? filterList.length : counts}条数据`"></el-alert>
    <el-alert type="info" show-icon :closable="false" v-else :title="`一共有${filterList.length ? filterList.length : QueryList.length}条数据`"></el-alert>

    <!-- 表格 -->
    <el-table style="width: 100%;" class="el-table" :data="filterList.length ? filterList : QueryList">
      <el-table-column label="试题编号" width="115" prop="number"></el-table-column>
      <el-table-column label="学科" width="115" prop="subject"></el-table-column>
      <el-table-column label="目录" width="106" prop="catalog"></el-table-column>
      <el-table-column label="题型" width="106" prop="questionType">
        <template slot-scope="{row}">
          {{formatterQuestionType(row.questionType)}}
        </template>
      </el-table-column>
      <el-table-column ref="formatHTML" label="题干" width="240" prop="question"></el-table-column>
      <el-table-column label="录入时间" width="160" prop="addDate">
        <!-- 所用与插槽 -->
        <template slot-scope="{row:{addDate}}">
          {{time(addDate)}}
        </template>
      </el-table-column>
      <el-table-column label="难度" width="100" prop="difficulty">
        <template slot-scope="{row}">
          {{formatterDifficulty(row.difficulty)}}
        </template>
      </el-table-column>
      <el-table-column label="录入人" width="115" prop="creator"></el-table-column>
      <el-row v-if="isShow">
        <el-table-column label="审核状态" width="115" prop="chkState" :formatter="formatChkState"></el-table-column>
        <el-table-column label="审核意见" width="115" prop="chkRemarks"></el-table-column>
        <el-table-column label="审核人" width="115" prop="chkUser"></el-table-column>
        <el-table-column label="发布状态" width="115" prop="publishState" :formatter="formPublishState"></el-table-column>
      </el-row>
      <el-table-column label="操作" v-if="!isFixed" width="200">
        <template slot-scope="{row}">
          <el-button type="primary" icon="el-icon-view" circle plain @click="preview(row)" title="预览"></el-button>
          <el-button type="success" icon="el-icon-edit" circle plain @click="$router.push(`/questions/new?id=${row.id}`)" title="修改"></el-button>
          <el-button type="danger" icon="el-icon-delete" circle plain @click="delTitle(row)" title="删除"></el-button>
          <el-button type="warning" icon="el-icon-check" circle plain @click="addBank(row.id)" title="加入精选"></el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" v-else fixed="right" width="200">
        <template slot-scope="{row}">
          <el-row type="flex" justify="space-between">
            <el-link type="primary" :underline="false" style="font-size: 12px;" @click="preview(row)">预览</el-link>
            <el-link :type="row.chkState ? 'info' : 'primary'" :underline="false" style="font-size: 12px;" @click="audit(row)" :disabled="row.chkState ? true : false">审核</el-link>
            <el-link :type="row.publishState !== 2 ? 'primary' : 'info'" :underline="false" style="font-size: 12px;" @click="$router.push(`/questions/new?id=${row.id}`)" :disabled="row.publishState !== 2 ? false : true">修改</el-link>
            <el-link type="primary" :underline="false" style="font-size: 12px;" v-if="true" @click="shelves(row)">{{row.publishState !== 2 ? '上架' : '下架'}}</el-link>
            <el-link :type="row.publishState !== 2 ? 'primary' : 'info'" :underline="false" style="font-size: 12px;" @click="delTitle(row)" :disabled="row.publishState !== 2 ? false : true">删除</el-link>
          </el-row>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页器 -->
    <el-row type="flex" justify="end">
      <el-pagination
        background
        layout="prev, pager, next, sizes, jumper"
        :total="counts"
        @size-change="sizeChange"
        @current-change="currentChange"
        :page-sizes="[1, 10, 30, 50]"
        ></el-pagination>
    </el-row>

    <!-- 预览弹层 -->
    <el-dialog title="题目预览" :visible="showDialog" @close="shutDown">
        <el-row type="flex" justify="space-between" class="popups">
          <el-col :span="6"><span>【题型】 : {{formatterQuestionType(titleDetails.questionType)}}题</span></el-col>
          <el-col :span="6"><span>【编号】 : {{titleDetails.id}}</span></el-col>
          <el-col :span="6"><span>【难度】 : {{formatterDifficulty(titleDetails.difficulty)}}</span></el-col>
          <el-col :span="6"><span>【标签】 : {{titleDetails.tags}}</span></el-col>
        </el-row>
        <el-row type="flex" justify="space-between">
          <el-col :span="6"><span>【学科】 : {{titleDetails.subjectName}}</span></el-col>
          <el-col :span="6"><span>【目录】 : {{titleDetails.directoryName}}</span></el-col>
          <el-col :span="6"><span>【方向】 : {{titleDetails.direction}}</span></el-col>
          <el-col :span="6"></el-col>
        </el-row>
        <hr />
        <el-row>
          <p>【题干】：</p>
          <p v-html="titleDetails.question"></p>
        </el-row>
        <!-- 单选 -->
        <el-row v-if="titleDetails.questionType === '1'">
          <p>{{formatterQuestionType(titleDetails.questionType)}}题 - 选项：（以下选中的选项为正确答案）</p>
          <p v-for="item in details.options" :key="item.id">
            <el-radio :value="item.isRight ? true : false" :label="true">{{item.title}}</el-radio>
          </p>
        </el-row>
        <!-- 多选 -->
        <el-row v-if="titleDetails.questionType === '2'">
            <p v-for="item in details.options" :key="item.id">
              <el-checkbox :checked="item.isRight ? true : false" :label="item.title">{{item.title}}</el-checkbox>
            </p>
        </el-row>
        <!-- 简答 -->
        <el-row v-if="titleDetails.questionType === '3'">
          <el-checkbox-group :value="[]">
            <el-checkbox label="复选框 A"></el-checkbox>
            <el-checkbox label="复选框 B"></el-checkbox>
            <el-checkbox label="复选框 C"></el-checkbox>
          </el-checkbox-group>
        </el-row>
        <hr />
        <el-row type="flex" justify="start" align="top">
          <span>【参考答案】：</span>
          <el-button type="danger" size="small" @click="videoPlay = true">视频答案预览</el-button>
        </el-row>
        <el-row>
          <video :src="details.videoURL" v-if="videoPlay" controls="true" style="width: 400px; height: 300px;"></video>
        </el-row>
        <hr />
        <el-row type="flex" align="middle">
          <span v-html="`【答案解析】：${titleDetails.answer}`"></span>
        </el-row>
        <hr />
        <el-row type="flex" align="middle">
          <p>【题目备注】：{{details.remarks}}</p>
        </el-row>
      <el-row slot="footer" type="flex" justify="end">
        <el-button @click="shutDown" type="primary">关闭</el-button>
      </el-row>
    </el-dialog>

    <!-- 审核弹层 -->
    <questions-check :isShow.sync="isShowDialog" :topicData="topicData" />
  </div>
</template>

<script>
import dayjs from 'dayjs'
import { questionType, difficulty, direction } from '@/api/hmmm/constants'
import { datas } from '@/api/hmmm/citys.js'
import { list as TagsList } from '@/api/hmmm/tags'
import { list as DirectoryList } from '@/api/hmmm/directorys'
import { list as SubjectsList } from '@/api/hmmm/subjects'
// 获取录入人列表
import { list as UserList } from '@/api/base/users'
// 审核弹层组件
import QuestionsCheck from '@/module-hmmm/components/questions-check'
// 审核
import { choicePublish, detail } from '@/api/hmmm/questions'

export default {
  props: {
    isShow: {
      type: Boolean,
      default: false
    },
    list: {
      type: Array,
      required: true
    },
    counts: {
      type: Number,
      required: true
    },
    pagination: {
      type: Object,
      required: true
    },
    titleDetails: {
      type: Object
    },
    isFixed: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      QueryList: this.list || [],
      formList: {
        // 学科
        discipline: '',
        // 目录
        directory: '',
        // 标签
        label: '',
        // 关键字
        keyWords: '',
        // 题目类型
        type: '',
        // 难度
        difficulty: '',
        // 方向
        direction: '',
        // 录入人
        person: '',
        // 题目
        title: '',
        // 企业
        enterprise: '',
        // 城市
        city: ['', '']
      },
      showDialog: false,
      isShowDialog: false,
      videoPlay: false,
      datas,
      direction,
      questionType,
      difficulty,
      tags: [],
      directory: [],
      // 课程
      subjects: [],
      paginationObj: this.pagination,
      // 录入人
      entryPeople: [],
      // 审核试题数据
      topicData: {},
      // 题目详情
      details: {},
      filterList: []
    }
  },
  methods: {
    // Tab标签页切换
    handleClick (tag, event) {
      const id = event.target.id
      // 全部
      if (id === 'tab-all') {
        this.QueryList = this.list
      }
      // 待审核
      if (id === 'tab-reviewed') {
        const reviewedData = [...this.list].filter(item => item.chkState === 0)
        this.QueryList = reviewedData
      }
      // 已审核
      if (id === 'tab-approved') {
        const approvedData = [...this.list].filter(item => item.chkState === 1)
        this.QueryList = approvedData
      }
      // 已拒绝
      if (id === 'tab-reject') {
        const rejectData = [...this.list].filter(item => item.chkState === 2)
        this.QueryList = rejectData
      }
    },
    // 获取录入人列表
    async getUserList () {
      this.entryPeople = (await UserList()).data.list
    },
    // 重置表单
    resetForm () {
      this.filterList = []
      this.$emit('searchTopic')
      Object.keys(this.formList).forEach(item => {
        this.formList[item] = item === 'city' ? [] : ''
      })
    },
    // 格式化时间
    time (time) {
      return dayjs(time).format('YYYY-MM-DD HH:mm:ss')
    },
    // 题型
    formatterQuestionType (cellValue) {
      const obj = questionType.find(({ value }) => (value === Number(cellValue)))
      return obj ? obj.label : ''
    },
    // 难度
    formatterDifficulty (cellValue) {
      const obj = difficulty.find(({ value }) => value === Number(cellValue))
      return obj ? obj.label : ''
    },
    // 删除
    delTitle (data) {
      this.$emit('delTitle', data)
    },
    // 加入精选题库
    addBank (id) {
      this.$emit('addBank', { id, choiceState: 1 })
    },
    // 关闭弹层
    shutDown () {
      this.videoPlay = this.showDialog = false
    },
    // 预览弹层
    async preview (data) {
      // console.log(await detail(data))
      const { data: list } = await detail(data)
      this.details = list
      this.showDialog = true
      // console.log(data)
      this.$emit('preview', data)
    },
    // 获取标签列表
    async getTagsList () {
      this.tags = (await TagsList()).data.items
      // console.log()
    },
    // 获取目录列表
    async getDirectoryList () {
      this.directory = (await DirectoryList({ pagesize: 1000 })).data.items
    },
    // 获取学科列表
    async getSubjectsList () {
      this.subjects = (await SubjectsList({ pagesize: 1000 })).data.items
      // console.log(this.subjects)
    },
    // 每页显示多少条
    sizeChange (val) {
      this.paginationObj.pagesize = val
      this.$emit('pageChange', this.paginationObj)
    },
    // 当前页数
    currentChange (val) {
      this.paginationObj.page = val
      this.$emit('pageChange', this.paginationObj)
    },
    // 搜题
    async searchTopic () {
      // 没有关键字
      if (!this.formList.keyWords) return this.$emit('searchTopic', { subjectID: this.formList.discipline })
      // 有关键字没有学科
      if (this.formList.keyWords && !this.formList.discipline) {
        this.QueryList = this.QueryList.filter(item => item.question.includes(this.formList.keyWords))
      }
      // 有学科并且有关键字
      if (this.formList.keyWords && this.formList.discipline) {
        await this.$emit('searchTopic', { subjectID: this.formList.discipline })
        this.filterList = this.QueryList.filter(item => item.question.includes(this.formList.keyWords))
      }
    },

    /**
     * 精选操作流程
     * 1.点击审核 - 审核通过 - 禁用审核按钮
     * 2.点击上架 - 禁用修改和删除按钮 - 显示下架
     * 3.点击下架 - 解除禁用 - 显示上架
     *
     */

    // 精选题库
    // 审核
    async audit (data) {
      this.isShowDialog = true
      this.topicData = data
    },
    // 上架 / 下架
    shelves (data) {
      // 上架
      if (data.publishState === 0 || data.publishState === 1) {
        this.$confirm('您确定上架这道题吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          data.publishState = 2
          const { data: { success } } = await choicePublish(data)
          if (!success) return this.$message.error('上架出错')
          this.$emit('updateList')
          this.$message.success('上架成功')
        }).catch(() => {
          this.$message.info('取消了操作')
        })
      }
      // 下架
      if (data.publishState === 2) {
        this.$confirm('您确定下架这道题吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async () => {
          data.publishState = 1
          const { data: { success } } = await choicePublish(data)
          if (!success) return this.$message.error('下架出错')
          this.$emit('updateList')
          this.$message.success('下架成功')
        }).catch(() => {
          this.$message.info('取消了操作')
        })
      }
    },
    // 格式化 - 审核状态
    formatChkState (row, column, cellValue, index) {
      if (cellValue === 0) return '待审核'
      if (cellValue === 1) return '已审核'
      if (cellValue === 2) return '已拒绝'
      return ''
    },
    // 格式化 - 发布状态
    formPublishState (row, column, cellValue, index) {
      if (cellValue === 0) return '待发布'
      if (cellValue === 1) return '已下架'
      if (cellValue === 2) return '已发布'
      return ''
    }
  },
  computed: {
    area () {
      const city = this.formList.city
      if (!city[0]) return []
      return this.datas.filter(item => {
        if (city[0] === item.city) return item.area
      })[0]
    }
  },
  watch: {
    paginationObj: {
      deep: true,
      handler (newVal) {
        this.pagination = newVal
      }
    },
    list: {
      deep: true,
      handler (newVal) {
        this.QueryList = newVal
      }
    }
  },
  created () {
    this.getTagsList()
    this.getDirectoryList()
    this.getSubjectsList()
    this.getUserList()
  },
  components: {
    QuestionsCheck
  }
}
</script>

<style scoped>
  .container {
    background-color: #fff;
    padding: 20px;
  }
  .el-table {
    margin: 20px 0;
  }
  .popups {
    padding: 20px 0;
  }

</style>
